<template>
  <div class="passwoed">
    <el-dialog v-model="dialogVisible" title="修改密码" width="20%" :before-close="handleClose">
      <el-input
        v-model="input1"
        placeholder="新密码"
        type="password"
        show-password
        style="margin-bottom: 15px"
      />
      <el-input v-model="input2" type="password" show-password placeholder="确认密码" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="confirm"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus';
import { ref } from 'vue';
import { editUserApi } from '@/service/api';
import { localCache } from '@/utils/cache';
import { useRouter } from 'vue-router';

const user = localCache.getCache('user');

const dialogVisible = ref(false);
const input1 = ref('');
const input2 = ref('');
const router = useRouter();

const handleClose = () => {
  dialogVisible.value = false;
  input1.value = '';
  input2.value = '';
};

const confirm = async () => {
  if (input1.value.length <= 6) return ElMessage.warning('密码长度必须大于6个字符');
  if (input1.value !== input2.value) return ElMessage.warning('两次密码不一致');
  const res: Res = await editUserApi({ id: user._id, password: input1.value });
  if (res.code !== 201) return ElMessage.error(res.msg);
  ElMessage.success('修改成功，请重新登录');
  localCache.removeCache('token');
  localCache.removeCache('user');
  router.push('/login');
};

defineExpose({ dialogVisible });
</script>

<style scoped lang="less"></style>
